<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "{{%sms_tpl}}".
 *
 * @property string $id
 * @property string $tpl_type 模板类型：aliyun(阿里云)
 * @property string $tpl_label 模板标签名，如登录验证码：login
 * @property string $tpl_sign 模板sign
 * @property string $tpl_code 模板CODE
 * @property string $tpl_name 模板中文名称
 * @property string $tpl_param 模板中参数对照传参，json格式如模板有参数`${code}`：{"${code}": "captcha"}
 * @property string $tpl_content 模板内容
 * @property string $tpl_remark 模板说明备注
 * @property string $created_at
 * @property string $updated_at
 */
class SmsTpl extends BaseActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%sms_tpl}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['tpl_type', 'tpl_label', 'tpl_sign', 'tpl_code', 'tpl_name', 'created_at', 'updated_at'], 'required'],
            [['created_at', 'updated_at'], 'safe'],
            [['tpl_type'], 'string', 'max' => 10],
            [['tpl_label', 'tpl_sign', 'tpl_code', 'tpl_name'], 'string', 'max' => 30],
            [['tpl_param'], 'string', 'max' => 500],
            [['tpl_content', 'tpl_remark'], 'string', 'max' => 250],
            [['tpl_type', 'tpl_label'], 'unique', 'targetAttribute' => ['tpl_type', 'tpl_label']],
        ];
    }

    /**
     * 创建
     * @return bool
     */
    public function create()
    {
        $this->created_at = $this->updated_at = date('Y-m-d H:i:s');
        if ($this->validate()) {
            return $this->save(false);
        }
        return false;
    }

    /**
     * 更新
     * @return bool
     */
    public function updateRow()
    {
        $this->updated_at = date('Y-m-d H:i:s');

        if ($this->validate() && $this->save(false)) {
            $key = Yii::$app->util->cacheKey("{$this->tpl_type}_{$this->tpl_label}");
            Yii::$app->getCache()->set($key, $this->toArray());
            return true;
        }
        return false;
    }
}
